﻿using System;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Input;
using WickedFlame.Core;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using WickedFlame.Util.Events;

namespace WickedFlame.Util.Controls
{
	[TemplatePart(Name="PART_CloseButton",Type=typeof(Button))]
    public class CanvasSelectionButton :  ContentControl
    {
		Button closeButton;

		//public event EventHandler Selected;
		//public event CloseCanvasEventHandler CloseCanvas;
        
		//static object syncRoot = new object();

        static CanvasSelectionButton()
        {
            DefaultStyleKeyProperty.OverrideMetadata(typeof(CanvasSelectionButton), new FrameworkPropertyMetadata(typeof(CanvasSelectionButton)));
        }

        public CanvasSelectionButton()
        {
        }

        public override void OnApplyTemplate()
        {
			if (closeButton != null)
			{
				closeButton.Click -= new RoutedEventHandler(CloseButton_Click);
				closeButton = null;
			}

            base.OnApplyTemplate();

			closeButton = GetTemplateChild("PART_CloseButton") as Button;
			if(closeButton!=null)
				closeButton.Click += new RoutedEventHandler(CloseButton_Click);
        }

		void CloseButton_Click(object sender, RoutedEventArgs e)
		{
			//var lb = FindVisualParent<ListBox>(this);
			//var cm = lb.DataContext as CanvasManager;
			var cm = FindVisualParent<ListBox>(this).DataContext as CanvasManager;
			var vi = DataContext as VectorImage;

			if (cm == null || vi == null)
				return;

			cm.Remove(vi);
			//if (CloseCanvas != null)
			//    CloseCanvas(this, new CloseCanvasEventArgs(Canvas));
		}

		public bool IsDirty
		{
			get
			{
				return (bool)GetValue(IsDirtyProperty);
			}
			set
			{
				SetValue(IsDirtyProperty, value);
			}
		}
		public static readonly DependencyProperty IsDirtyProperty =
			DependencyProperty.Register("IsDirty", typeof(bool), typeof(CanvasSelectionButton), new PropertyMetadata(false));


		//public VectorImage VectorImage
		//{
		//    get
		//    {
		//        return (VectorImage)GetValue(VectorImageProperty);
		//    }
		//    set
		//    {
		//        SetValue(VectorImageProperty, value);
		//    }
		//}
		//public static readonly DependencyProperty VectorImageProperty =
		//    DependencyProperty.Register("VectorImage", typeof(VectorImage), typeof(CanvasSelectionButton), new PropertyMetadata(null));

		public static T FindVisualParent<T>(UIElement element) where T : UIElement
		{
			UIElement parent = element; while (parent != null)
			{
				T correctlyTyped = parent as T; if (correctlyTyped != null)
				{
					return correctlyTyped;
				}
				parent = VisualTreeHelper.GetParent(parent) as UIElement;
			} return null;
		}
    }
}
